package com.anti.jdbc.core.executor.supporrt;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.support.KeyHolder;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-3-13
 */
public class JdbcBuilder {

    private JdbcTemplate jdbcTemplate;

    private boolean useLocalCache;

    private boolean showSQL;

    protected Log logger;


    public <T> JdbcBuilder(JdbcTemplate jdbcTemplate, boolean useLocalCache, boolean showSQL, String interfaceClass) {
        this.jdbcTemplate= jdbcTemplate;
        this.useLocalCache=useLocalCache;
        this.showSQL=showSQL;
        logger = LogFactory.getLog(interfaceClass);
    }

    public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)throws DataAccessException {
        int rows= jdbcTemplate.update(psc, generatedKeyHolder);
        return rows;
    }

    public int update(String sql, PreparedStatementSetter pss) throws DataAccessException {
        getShowSQL(sql, null);
        int rows=jdbcTemplate.update(sql, pss);
        return rows;
    }


    public int[] batchUpdate(String sql, final BatchPreparedStatementSetter pss) throws DataAccessException {
        getShowSQL(sql, null);
        int[] rows=jdbcTemplate.batchUpdate(sql, pss);
        return rows;
    }


    private void getShowSQL(String sql, Object[] parameters){
        if(showSQL||logger.isDebugEnabled()){
            if(logger.isDebugEnabled()) {
                logger.debug("==> SQL:[ " + sql + " ]");
            }else {
                logger.info("==> SQL:[ " + sql + " ]");
            }

            getParameters(parameters);
        }

    }

    protected void getParameters(Object[] parameters){
        String  params="";
        if(parameters!=null&& parameters.length>0){
            for(Object parameter:parameters){
                params+=parameter+",";
            }
            params = params.substring(0, params.length()-1);
            if(logger.isDebugEnabled()) {
                logger.debug("==> parameters: " + params + " ");
            }else {
                logger.info("==> parameters: " + params + " ");
            }

        }

    }
}
